import threading
import tkinter as tk
import webbrowser  # 添加 webbrowser 导入

import uvicorn
import webview

from main import app as fastapi_app


class Api:
    def openExternal(self, url):
        """打开外部链接"""
        webbrowser.open(url)


class DesktopApp:
    def __init__(self):
        self.port = 8088  # 使用固定的吉利端口号
        self.window = None
        self.api = Api()  # 创建 API 实例

    @staticmethod
    def get_unused_port():
        """获取未被使用的端口"""
        return 8088  # 直接返回固定端口

    def start_server(self):
        """启动FastAPI服务器"""
        t = threading.Thread(
            target=uvicorn.run,
            args=(fastapi_app,),  # 使用重命名后的fastapi_app
            kwargs={"port": self.port}
        )
        t.daemon = True
        t.start()

    def create_window(self):
        """创建应用程序窗口"""
        # 使用tkinter获取屏幕尺寸
        root = tk.Tk()
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        root.destroy()

        # 设置窗口初始大小为屏幕的85%
        window_width = int(screen_width * 0.85)
        window_height = int(screen_height * 0.85)

        window = webview.create_window(
            'Cursor Task',
            f'http://localhost:{self.port}',
            width=window_width,
            height=window_height,
            resizable=True,
            frameless=False,  # 使用默认外框
            min_size=(800, 600),
            background_color='#FFFFFF',
            js_api=self.api  # 注入 API 实例
        )

        self.window = window
        return window

    def run(self):
        """运行应用程序"""
        self.start_server()
        self.create_window()
        webview.start()


if __name__ == '__main__':
    desktop_app = DesktopApp()  # 使用更明确的变量名
    desktop_app.run()
